package cc.zy.base.hr.controller;

import cc.zy.base.businesses.entity.College;
import cc.zy.base.common.annotation.ControllerEndpoint;
import cc.zy.base.common.controller.BaseController;
import cc.zy.base.common.entity.FebsConstant;
import cc.zy.base.common.entity.FebsResponse;
import cc.zy.base.common.entity.QueryRequest;
import cc.zy.base.common.exception.FebsException;
import cc.zy.base.common.utils.DateUtil;
import cc.zy.base.common.utils.FebsUtil;
import cc.zy.base.hr.entity.TrainningBatch;
import cc.zy.base.hr.entity.TrainningBatch;
import cc.zy.base.hr.service.ITrainningBatchService;
import cc.zy.base.hr.service.impl.TrainningBatchImpl;
import com.aliyun.oss.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.mchange.lang.IntegerUtils;
import com.wuwenze.poi.ExcelKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;

@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class TrainningBatchController extends BaseController {

    @Resource
    private final ITrainningBatchService trainningBatchService;

    /**
     * @description: 不能为特殊字符
     * @author pengfeng
     * @date: 2022/3/8 20:51
     */
    private final String CHAR = "^[\u4E00-\u9FA5A-Za-z0-9-（）()]+$";

    /**
     *
     * @description: 不能为特殊字符
     * @author pengfeng
     * @date: 2022/3/8 20:51
     */
    private final Integer FINALIZATION = 0;


    /**
     * @description: 跳转添加子页面
     * @return:
     * @author pengfeng
     * @date: 2022/3/7 16:42
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "trainningBatch/add")
    public String trainningBatchAdd() {
        return FebsUtil.hrView("trainningBatch/trainningBatchAdd");
    }

    /**
     * @description: 跳转到修改子页面
     * @param: null
     * @return:
     * @author pengfeng
     * @date: 2022/3/7 16:47
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "trainningBatch/update/{id}")
    public String trainningBatchUpdate(@PathVariable Integer id, Model model) {
        resolveTrainningBatchModel(id, model, false);
        return FebsUtil.hrView("trainningBatch/trainningBatchUpdate");
    }

    private void resolveTrainningBatchModel(Integer id, Model model, Boolean transform) {
        TrainningBatch trainningBatch = trainningBatchService.findById(id);
        if (trainningBatch.getCreateDate() != null) {
            model.addAttribute("createDateTime", DateUtil.getDateFormat(trainningBatch.getCreateDate(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
        if (trainningBatch.getLastModifyDate() != null) {
            model.addAttribute("updateDateTime", DateUtil.getDateFormat(trainningBatch.getLastModifyDate(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }

        model.addAttribute("trainningBatch", trainningBatch);
    }

    /**
     * @description: 跳转到详情子页面
     * @param: null
     * @return:
     * @author pengfeng
     * @date: 2022/3/7 16:47
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "trainningBatch/detail/{id}")
    public String trainningBatchDetail(@PathVariable Integer id, Model model) {
        resolveTrainningBatchModel(id, model, true);
        return FebsUtil.hrView("trainningBatch/trainningBatchDetail");
    }

    /**
     * 跳转编辑试题页面
     *
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "examineSimple/examineSimpleAddOrUpdate")
    public String goExamineSimpleAddOrUpdate() {
        return FebsUtil.hrView("examineSimple/examineSimpleAddOrUpdate");
    }


    /**
     * 查询（分页）
     *
     * @param request
     * @param trainningBatch
     * @return
     */
    @GetMapping("trainningBatch/list")
    @ResponseBody
    public FebsResponse trainningBatchList(QueryRequest request, TrainningBatch trainningBatch) {

        log.debug("前台传来的对象是：" + trainningBatch);
        Map<String, Object> dataTable = getDataTable(trainningBatchService.listTrainningBatchs(request, trainningBatch));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 增加（不能为特殊字符校验， id生成规则）
     *
     * @param trainningBatch
     * @return
     */
    @PostMapping("trainningBatch/add")
    @ResponseBody
    @ControllerEndpoint(operation = "新增培训批次", exceptionMessage = "新增批次异常")
    public FebsResponse addTrainningBatch(@Valid TrainningBatch trainningBatch) {

        log.debug("前台传来的对象是: ", trainningBatch);
        boolean match = FebsUtil.match(CHAR, trainningBatch.getTrainningName());

        if(!match){
            return new FebsResponse().fail().message("培训批次不能为特殊字符");
        }

        trainningBatch.setTrainningStatusId(FINALIZATION);
        trainningBatch.setTrainningStatusName(null);
        trainningBatch.setCreateUserId(FebsUtil.getCurrentUser().getUserId());
        trainningBatch.setLastModifyUserId(FebsUtil.getCurrentUser().getUserId());
        trainningBatch.setCreateUserId(FebsUtil.getCurrentUser().getUserId());

        trainningBatchService.createTrainningBatch(trainningBatch);
        return new FebsResponse().success();
    }

    /**
     * 判断传入P批次名称是否重复
     *
     * @param trainningName
     * @return
     */
    @GetMapping("trainningBatch/isRepetitive")
    @ResponseBody
    public Boolean isRepetitive(String trainningName) {
        return trainningBatchService.isRepetitive(trainningName);
    }

    /**
     * 修改批次
     *
     * @param trainningBatch
     * @return
     */
    @PostMapping("trainningBatch/update")
    @ControllerEndpoint(operation = "修改批次", exceptionMessage = "修改批次异常")
    @ResponseBody
    public FebsResponse updateTrainningBatch(@Valid TrainningBatch trainningBatch) {

        log.debug("前台传来的对象是: ", trainningBatch);
        boolean match = FebsUtil.match(CHAR, trainningBatch.getTrainningName());
        if(!match){
            return new FebsResponse().fail().message("批次不能为特殊字符");
        }

        log.debug("修改批次id：" + trainningBatch.getId());
        if (trainningBatch.getId() == null) {
            throw new FebsException("批次ID为空");
        }

        trainningBatch.setLastModifyUserId(FebsUtil.getCurrentUser().getUserId());
        trainningBatchService.updateTrainningBatch(trainningBatch);
        return new FebsResponse().success();
    }

    /**
     * 删除批次
     *
     * @param trainningBatchIds
     * @return
     */
    @GetMapping("trainningBatch/delete/{trainningBatchIds}")
    @ControllerEndpoint(operation = "删除批次", exceptionMessage = "删除批次异常")
    @ResponseBody
    public FebsResponse deleteTrainningBatchs(@NotBlank(message = "{required}") @PathVariable String trainningBatchIds) {
        log.debug("删除批次id数组：" + trainningBatchIds);

        String[] ids = trainningBatchIds.split(StringPool.COMMA);
        trainningBatchService.deleteTrainningBatchs(ids);
        return new FebsResponse().success();
    }

    /**
     * 导出excel表
     *
     * @param response
     * @param trainningBatch
     */
    @GetMapping("trainningBatch/excel")
    @ControllerEndpoint(exceptionMessage = "导出Excel异常")
    public void export(HttpServletResponse response, TrainningBatch trainningBatch) {
        log.debug(String.format("response = %s", response));
        log.debug(String.format("trainningBatch = %s", trainningBatch));

        List<TrainningBatch> trainningBatchs = trainningBatchService.listTrainningBatchListNotPage(trainningBatch);
        ExcelKit.$Export(TrainningBatch.class, response).downXlsx(trainningBatchs, false);
    }

    /**
     * 转换定稿
     *
     * @param trainningBatchIds
     * @return
     */
    @GetMapping("trainningBatch/draftToExecte/{trainningBatchIds}")
    @ControllerEndpoint(operation = "转换定稿", exceptionMessage = "转换定稿异常")
    @ResponseBody
    public FebsResponse draftToExecte(@NotBlank(message = "{required}") @PathVariable String trainningBatchIds) {
        log.debug("转换定稿的批次id数组：" + trainningBatchIds);

        System.out.println(trainningBatchIds);
        if(trainningBatchIds == null){
            return new FebsResponse().fail().message("批次id不能为null");
        }
        Integer trainningBatchId = Integer.valueOf(trainningBatchIds);
        trainningBatchService.draftToExecute(trainningBatchId);
        return new FebsResponse().success();
    }
}
